package zju.xmsx.acm.search.back.dao;

import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.update.UpdateRequest;
import org.elasticsearch.action.update.UpdateResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;
import zju.xmsx.acm.search.back.dto.UpdateContent;

import javax.annotation.Resource;
import java.io.IOException;

@Component
public class ESUpdaterImpl implements ESUpdater{

    @Resource
    @Qualifier("client")
    private RestHighLevelClient client;

    @Override
    public UpdateResponse updateDoc(UpdateContent update) {
        UpdateRequest updateRequest = new UpdateRequest();
        updateRequest.index(update.getIndex());
        updateRequest.id(update.getId());
        updateRequest.doc(update.getContent());
        try {
            return client.update(updateRequest, RequestOptions.DEFAULT);
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

    @Override
    public BulkResponse bulkUpdate(UpdateContent[] updates) {
        BulkRequest bulk = new BulkRequest();
        for (UpdateContent update: updates){
            UpdateRequest updateRequest = new UpdateRequest();
            updateRequest.index(update.getIndex());
            updateRequest.id(update.getId());
            updateRequest.doc(update.getContent());
            bulk.add(updateRequest);
        }

        try {
            return client.bulk(bulk, RequestOptions.DEFAULT);
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }
}
